package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class CartFragment extends Fragment {
    private RecyclerView rvCart;
    private CheckBox cbSelectAll;
    private TextView tvTotalPrice;
    private Button btnCheckout;
    private CartAdapter cartAdapter;
    private List<Product> productList = new ArrayList<>();
    private String creatOrderURL=SeverURL.URL+"/create_order";


    public CartFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shoping_cart, container, false);


        initViews(view);
        initData();
        setupRecyclerView();
        setupListeners();
        updateTotalPrice();

        return view;
    }

    private void initViews(View view) {
        rvCart = view.findViewById(R.id.rv_cart);
        cbSelectAll = view.findViewById(R.id.cb_select_all);
        tvTotalPrice = view.findViewById(R.id.tv_total_price);
        btnCheckout = view.findViewById(R.id.btn_checkout);
    }

    public void reClick(){
        initData();
        setupRecyclerView();
    }

    private void initData() {
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("cart"+username, Context.MODE_PRIVATE);

        // 2. 获取现有的购物车列表（如果有）
        String cartJson = sharedPreferences.getString("cart_items", "[]");
        Gson gson = new Gson();
        Type type = new TypeToken<List<Product>>() {}.getType();
        productList = gson.fromJson(cartJson, type);
    }

    private void setupRecyclerView() {
        rvCart.setLayoutManager(new LinearLayoutManager(getContext()));
        cartAdapter = new CartAdapter(productList, new CartAdapter.OnItemClickListener() {
            @Override
            public void onSelectChange(int position, boolean isSelected) {
                updateTotalPrice();
                checkSelectAllStatus();
            }

            @Override
            public void onQuantityChange(int position, int quantity) {
                updateTotalPrice();
                updateProductCount();
            }
        });
        rvCart.setAdapter(cartAdapter);
    }

    private void setupListeners() {
        // 先移除监听，避免递归调用
        cbSelectAll.setOnCheckedChangeListener(null);
        cbSelectAll.setChecked(false); // 初始状态

        // 设置全选监听
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (cartAdapter != null) {
                cartAdapter.selectAll(isChecked); // 更新所有商品的选中状态
                updateTotalPrice(); // 更新总价
            }
        });

        // 结算按钮
        btnCheckout.setOnClickListener(v -> {
            List<Product> selectedProducts = getSelectedProducts();
            if (selectedProducts.isEmpty()) {
                Toast.makeText(getContext(), "请选择要结算的商品", Toast.LENGTH_SHORT).show();
            } else {
                checkout(selectedProducts);
            }
        });
    }

    private void updateTotalPrice() {
        double totalPrice = 0;
        int selectedCount = 0;

        for (Product product : productList) {
            if (product.isSelected()) {
                totalPrice += product.getPrice() * product.getBuyCount();
                selectedCount++;
            }
        }

        tvTotalPrice.setText(String.format("合计: ¥%.2f", totalPrice));
        btnCheckout.setText(String.format("结算(%d)", selectedCount));
    }

    private void checkSelectAllStatus() {
        if (cartAdapter == null || productList.isEmpty()) {
            cbSelectAll.setChecked(false);
            return;
        }

        // 检查是否所有商品都被选中
        boolean allSelected = true;
        for (Product product : productList) {
            if (!product.isSelected()) {
                allSelected = false;
                break;
            }
        }

        // 更新全选 CheckBox 的 UI，但不触发监听
        cbSelectAll.setOnCheckedChangeListener(null); // 先移除监听，避免递归
        cbSelectAll.setChecked(allSelected);
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (cartAdapter != null) {
                cartAdapter.selectAll(isChecked);
                updateTotalPrice();
            }
        });
    }

    private List<Product> getSelectedProducts() {
        List<Product> selectedProducts = new ArrayList<>();
        for (Product product : productList) {
            if (product.isSelected()) {
                selectedProducts.add(product);
            }
        }
        return selectedProducts;
    }

    private void checkout(List<Product> selectedProducts) {
        // 检查Fragment是否已附加
        if (!isAdded() || getActivity() == null) {
            return;
        }

        // 检查selectedProducts是否为空
        if (selectedProducts == null || selectedProducts.isEmpty()) {
            showAlertDialog("提示", "请先选择商品");
            return;
        }

        SharedPreferences sharedPref = getActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        // 检查用户登录状态
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            showAlertDialog("提示", "请先登录");
            return;
        }

        // 构建请求数据
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("username", sharedPref.getString("username", null));
        requestData.put("password", sharedPref.getString("password", null));

        List<Map<String, Object>> items = new ArrayList<>();
        for (Product product : selectedProducts) {
            if (product != null) {
                Map<String, Object> item = new HashMap<>();
                item.put("productId", product.getId());
                item.put("quantity", product.getBuyCount());
                items.add(item);
            }
        }
        requestData.put("items", items);

        // 发送网络请求
        sendCheckoutRequest(new Gson().toJson(requestData));
    }

    private void showAlertDialog(String title, String message) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                new AlertDialog.Builder(getContext())
                        .setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
                        .show();
            });
        }
    }

    private void sendCheckoutRequest(String json) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .url(creatOrderURL)
                .post(RequestBody.create(json, MediaType.get("application/json")))
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showAlertDialog("错误", "请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body() != null ? response.body().string() : "";
                    JSONObject jsonObject = new JSONObject(responseData);
                    String status = jsonObject.optString("status");
                    String message = jsonObject.optString("message");

                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            if ("success".equals(status)) {
                                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                                // 清空购物车
                                productList.clear();
                                cartAdapter.notifyDataSetChanged();
                                updateProductCount();
                                updateTotalPrice();
                                cbSelectAll.setChecked(false);
                            } else {
                                showAlertDialog("提示", message);
                            }
                        });
                    }
                } catch (Exception e) {
                    showAlertDialog("错误", "解析响应失败: " + e.getMessage());
                }
            }
        });
    }

    public void updateProductCount() {
        SharedPreferences sharedPref =  requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("cart"+username, Context.MODE_PRIVATE);

        Gson gson = new Gson();

        String updatedCartJson = gson.toJson(productList);
        sharedPreferences.edit()
                .putString("cart_items", updatedCartJson)
                .apply();
        return;
    }
}